package com.yuan.user.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import com.alibaba.nacos.common.util.Md5Utils;
import com.yuan.user.util.MD5Util;
import com.yuan.user.util.OssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yuan.user.entity.UserEntity;
import com.yuan.user.service.UserService;
import com.yuan.common.utils.PageUtils;
import com.yuan.common.utils.R;
import org.springframework.web.multipart.MultipartFile;


/**
 * 
 *
 * @author yuanxiaoxu
 * @email 2815932281@qq.com
 * @date 2022-02-22 20:38:03
 */
@RestController
@RequestMapping("user/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private OssUtils ossUtils;
    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    public R info(@PathVariable("userId") Long userId){
		UserEntity user = userService.getById(userId);

        return R.ok().put("user", user);
    }
/**
     * 登录
     */
    @RequestMapping("/login")
    public R info(@RequestBody UserEntity userEntity){
		UserEntity user = userService.getByUname(userEntity.getUserName());
		if (user!=null){
            String s = MD5Util.md5Code(userEntity.getPassword(), 2);
            if (s.equals(user.getPassword())){
                //登陆成功 登录次数+1
                user.setLoginCount(user.getLoginCount()+1);
                userService.updateById(user);
                return R.ok().put("user", user);
            }
        }
		return R.error();
    }

    @RequestMapping("/upload")
    public R upload(MultipartFile file){
        R r = ossUtils.uploadFile(file);
        return r;
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user){
        String s = MD5Util.md5Code(user.getPassword(), 2);
        user.setPassword(s);
        user.setRegisterData(new Date());
        user.setLoginCount(0);
        user.setLastLoginData(null);
        user.setSalt("yuanxiaoxu");
        userService.save(user);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
		userService.updateById(user);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] userIds){
		userService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }

}
